import { Injectable } from '@angular/core';
import { v4 as uuid } from 'uuid';
import { I18NService } from '../core/api';
import { OptionItem } from '../select/interface';
import { FieldItem, RecommendedValue } from './interface';

@Injectable()
export class SearchService {
  readonly keyword = `keyword-${uuid()}`;
  constructor(private i18n: I18NService) {}
  getFilter(value: string, lvFields: FieldItem[]): OptionItem[] {
    return lvFields
      .filter((item): boolean => item.label.toLocaleLowerCase().indexOf(value.toLocaleLowerCase()) !== -1)
      .map((item): { disabled: boolean; label: string; value: string | number; isLeaf: true } => ({
        label: item.label,
        value: item.field,
        isLeaf: true,
        disabled: item.disabled,
      }));
  }

  getSearchFilters(filter: OptionItem[], recommendedSearch: OptionItem[]): OptionItem[] {
    return [
      ...(recommendedSearch.length
        ? [
            { label: this.i18n.get('recommendedSearch'), readonly: true, hoverDisabled: true, isLeaf: true },
            ...recommendedSearch,
          ]
        : []),
      ...(filter.length
        ? [{ label: this.i18n.get('filter'), readonly: true, hoverDisabled: true, isLeaf: true }, ...filter]
        : []),
    ];
  }

  getRecommendedSearch(
    value: string,
    lvFields: FieldItem[],
    searchConfig: { searchKeyWordAble: boolean; searchKeyWord: string },
  ): OptionItem[] {
    const textInput = lvFields.filter(
      (item): boolean =>
        item.type === 'textInput' && !item.searchDisable && item.modeChangeDisable && item.mode === 'contains',
    );
    return [
      ...(searchConfig.searchKeyWordAble
        ? [
            {
              label: this.i18n.get('include', [searchConfig.searchKeyWord, value]),
              value: {
                label: searchConfig.searchKeyWord,
                field: this.keyword,
                value,
              } as RecommendedValue,
              isLeaf: true,
            },
          ]
        : []),
      ...(textInput.length
        ? textInput.map((item): { label: any; value: RecommendedValue; isLeaf: true } => ({
            label: this.i18n.get('include', [item.label, value]),
            value: {
              label: item.label,
              field: item.field,
              value,
            } as RecommendedValue,
            isLeaf: true,
          }))
        : []),
    ];
  }
}
